<!--
 * @Author: 徐建辰
 * @Date: 2022-06-06 10:00:56
 * @LastEditTime: 2022-06-23 17:46:06
 * @LastEditors: xjc
 * @Description: 图像剪裁组件
-->
<template>
  <div class="cropper">
    <div class="cropper__img">
      <img :src="src" ref="imgRef" />
    </div>
    <div class="cropper__preview">
      <h4>图像预览</h4>
      <div class="cropper__preview__img" ref="previewRef" />
    </div>
  </div>
</template>

<script setup>
import {ref, watch, onMounted} from 'vue'
import Cropper from 'cropperjs'
// import 'cropperjs/dist/cropper.css'

// eslint-disable-next-line
const props = defineProps({
  src: {type: String, default: ''},
  compress: {type: Number, default: 1},
  aspectRatio: {type: Number, default: NaN}
})

const previewRef = ref(null)
const imgRef = ref(null)
const crop = ref(null)

watch(() => props.aspectRatio, newVal => crop.value.setAspectRatio(newVal))

onMounted(() => initCropper())

function initCropper() {
	crop.value = new Cropper(imgRef.value, {
		viewMode: 2,
		dragMode: 'move',
		responsive: false,
		aspectRatio: props.aspectRatio,
		preview: previewRef.value
	})
}
function setAspectRatio(aspectRatio){
	crop.value.setAspectRatio(aspectRatio)
}
function getCropData(cb, type='image/jpeg'){
	cb(crop.value.getCroppedCanvas().toDataURL(type, props.compress))
}
function getCropBlob(cb, type='image/jpeg'){
	crop.value.getCroppedCanvas().toBlob(blob => cb(blob), type, props.compress)
}
function getCropFile(cb, fileName='fileName.jpg', type='image/jpeg'){
	crop.value.getCroppedCanvas().toBlob(blob => {
		let file = new File([blob], fileName, {type: type})
		cb(file)
	}, type, props.compress)
}

// eslint-disable-next-line
defineExpose({getCropData, getCropBlob, getCropFile, setAspectRatio})
</script>

<style scoped lang="scss">
.cropper {
  height: 300px;
  .cropper__img {
    @include wh(400px, 100%);
    float: left;
    background: #ebeef5;
    img {
      display: none;
    }
  }
  .cropper__preview {
    width: 120px;
    margin-left: 20px;
    float: left;
    h4 {
      font-weight: normal;
      @include sc($font-size-small, $color-text-p);
      margin-bottom: 20px;
    }
    .cropper__preview__img {
      overflow: hidden;
      @include wh(120px, 120px);
      border: 1px solid #ebeef5;
    }
  }
}
</style>
